<template>
  <div class="home">
    <p>
      num: {{ num }} - nums: {{ nums }} - nums1: {{ nums1 }} - nums2:
      {{ nums2 }}
    </p>
    <p>result: {{ result }} - result1: {{ result1 }}</p>
    <p>user1: {{ user1 }}</p>
    <button @click="setNum">setNum</button>
    <button @click="testFunc">测试</button>
    <h3>res: {{ res }}</h3>
    <HelloWorld @setnum="receiveData" />
    <hr />
    <p>Pinia: {{ homeName }} - {{ homeAge }}</p>
    <button @click="changeHomeName">修改store</button>
    <button @click="resetHomeStore">重置store</button>
  </div>
</template>

<script lang="ts" setup>
import HelloWorld from "@/components/HelloWorld.vue";
import {
  ref,
  reactive,
  Ref,
  computed,
  ComputedRef,
  provide,
  toRefs,
} from "vue";
import { storeToRefs } from "pinia";
import { nameKey } from "@/types/index";
import { ageKey, userKey } from "../types/index";
import useHome from "@/stores/useHome";
const homeStore = useHome();
// const { homeName, homeAge } = toRefs(homeStore);

const { homeName, homeAge } = storeToRefs(homeStore);
console.log(homeName);

const changeHomeName = () => {
  // homeStore.homeName = Date.now() + ""; // this.$store.state.homeName = ""
  homeName.value = Date.now() + "";
  homeAge.value++;
};

const resetHomeStore = () => {
  homeStore.$reset(); // 重置store的状态为初始值
};

interface IUser {
  uname: string;
  uage: number;
  uother: any;
}

// ref类型的ts写法：
// const num: Ref<TStringNumber> = ref(100);
// 或者：
const num = ref<TStringNumber>(0);
const setNum: IDefaultFunction = (): void => {
  (num.value as number)++;
};

// reactive类型的ts写法：
const nums: number[] = reactive([1, 2, 3, 4, 5, 6]);
const nums1: (number | string | boolean)[] = reactive([1, 2, 3, "4", true, 6]);
const nums2: Array<number | string | boolean> = reactive([
  1,
  2,
  3,
  "4",
  true,
  6,
]);

const user: IUser = reactive({
  uname: "小明",
  uage: 20,
  uother: {
    a: 100,
  },
}); // 推荐写法
const user1 = reactive<IUser>({
  uname: "小明",
  uage: 20,
  uother: {
    a: 100,
  },
}); // 不推荐写法

// 计算属性的ts写法:
const result: ComputedRef<number> = computed(() => (num.value as number) + 200);
const result1 = computed<number>(() => (num.value as number) + 200);

const testFunc = (e: MouseEvent): void => {
  console.log((e.target as HTMLElement).innerText);
};

// 声明函数，接收子组件数据
const res = ref<number>(0);
const receiveData = (data: number): void => {
  res.value = data;
};

provide(nameKey, "小王");
provide(ageKey, 22);
provide(userKey, {
  uage: 100,
  uaddress: "郑州市",
});
</script>
